import fs from 'fs'
import path from 'path'
import ejs from 'ejs'

export async function generateCRUD(info: {
  tableName: string
  className: string
  fields: string[]
  name: string
}) {
  const { tableName, className, fields, name } = info
  const baseDir = path.resolve(process.cwd(), 'src')

  const controllerDir = path.join(baseDir, 'controller', name)
  const serviceDir = path.join(baseDir, 'service', name)

  ensureDir(controllerDir)
  ensureDir(serviceDir)

  const templates = [
    { type: 'controller', outDir: controllerDir },
    { type: 'service', outDir: serviceDir },
  ]

  for (const { type, outDir } of templates) {
    const tplPath = path.resolve(__dirname, `./templates/${type}.ts.ejs`)
    const outPath = path.join(outDir, `${className}${capitalize(type)}.ts`)

    const content = await ejs.renderFile(tplPath, info)
    fs.writeFileSync(outPath, content, 'utf8')
    console.log(`✅ 已生成：${outPath}`)
  }
}

function ensureDir(dir: string) {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true })
  }
}

function capitalize(s: string) {
  return s.charAt(0).toUpperCase() + s.slice(1)
}
